package com.dirk.happie.activities;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.dirk.happie.R;
import com.dirk.happie.beans.CompanyBean;
import com.dirk.happie.beans.FavoritesBean;
import com.dirk.happie.network.GetFavoritesTask;
import com.dirk.happie.network.GetUserTask;
import com.dirk.happie.network.RequestCompleteListener;
import com.dirk.happie.network.ResetPasswordTask;
import com.dirk.happie.network.SetNewUserTask;
import com.dirk.happie.utils.App;
import com.dirk.happie.utils.Availablity;
import com.dirk.happie.utils.Common;
import com.dirk.happie.utils.Keys;

public class LoginRegisterActivity extends Activity {

	public Dialog alertDialog;

	EditText usernameETL;
	EditText passwordETL;

	ScrollView svBackground;

	TextView sign_in;
	TextView reg;

	EditText userET;
	EditText passET;
	EditText verifyET;
	EditText nameET;
	EditText surnameET;
	EditText emailET;
	EditText phoneET;
	EditText streetET;
	EditText aptnoET;
	EditText zipET;
	EditText cityET;
	// EditText countryET;

	String userL = "";
	String passL = "";

	String username;
	String password;

	String name;
	String surname;
	String email;
	String street;
	String aptno;
	String zip;
	String city;
	String phone;
	// String country;

	String verPassword;
	boolean register;
	boolean second;

	public int dispWidth;
	public int dispHeight;

	private App mApp;

	private GetFavoritesTask getFavoritesTask = null;
	private GetUserTask getUserTask = null;
	private SetNewUserTask setNewUserTask = null;
	private ResetPasswordTask resetPasswordTask = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_login_register);

		this.mApp = ((App) getApplication());

		register = false;

		textViewListeners();

		editTextListeners();

		loginButtonListener();

		loginEditTextListeners();

		// backButtonListener();

		registerButtonListener();

		// footerMenuListeners();

	}

	@Override
	public void onResume() {
		super.onResume();
		second = false;
	}

	public void textViewListeners() {

		sign_in = (TextView) findViewById(R.id.sign_in);

		reg = (TextView) findViewById(R.id.reg);

		TextView versionTextView = (TextView) findViewById(R.id.versionText);
		PackageInfo pInfo;
		String version = getString(R.string.app_name);
		try {
			pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
			version = "Version " + pInfo.versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		versionTextView.setText(version);

		svBackground = (ScrollView) findViewById(R.id.scrollView1);
		// svBackground.setOnTouchListener(new OnTouchListener() {
		//
		// public boolean onTouch(View v, MotionEvent event) {
		// // TODO Auto-generated method stub
		// InputMethodManager imm = (InputMethodManager)
		// getSystemService(Context.INPUT_METHOD_SERVICE);
		// imm.hideSoftInputFromWindow(svBackground.getWindowToken(), 0);
		// return false;
		// }
		// });
	}

	private void loginEditTextListeners() {

		usernameETL = (EditText) findViewById(R.id.l_username);
		passwordETL = (EditText) findViewById(R.id.l_pass);

		usernameETL.setHint(R.string.email);
		passwordETL.setHint(R.string.password);

	}

	private void loginButtonListener() {

		Button resetPassBtn = (Button) findViewById(R.id.l_resetPassBtn);
		resetPassBtn.setText(R.string.resetPass);
		resetPassBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				username = usernameETL.getText().toString();

				if (username.equals(Keys.EMPTY_STRING)) {
					showErrorDialog(getString(R.string.empty_username));
					return;
				}

				resetPassword();
			}
		});
		Button loginButton = (Button) findViewById(R.id.l_loginBtn);
		loginButton.setText(R.string.login);
		loginButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				username = usernameETL.getText().toString();
				password = passwordETL.getText().toString();
				
				boolean isEmpty = false;
				if (username.equals(Keys.EMPTY_STRING)) {
					usernameETL.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_username));
				}

				if (password.equals(Keys.EMPTY_STRING)) {
					passwordETL.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_password));
				}

				if (isEmpty) {
					showErrorDialog(getString(R.string.fill_all_fields));
					return;
				}

				loginUser();

			}
		});
	}

	private void resetPassword() {
		resetPasswordTask = new ResetPasswordTask(LoginRegisterActivity.this);

		resetPasswordTask.setRequestCompleteListener(new RequestCompleteListener<String>() {

			@Override
			public void onSuccess(String result) {
				try {
					JSONArray jsonArray = new JSONArray(result);
					JSONObject json = jsonArray.getJSONObject(0);
					if (json.has("apimsg")) {
						showErrorDialog(json.getString("apimsg"));
					}
					if (json.has("error")) {
						showErrorDialog(json.getString("error") + "\n" + getString(R.string.please_register));
					}
				} catch (Exception e) {
				}

			}

			@Override
			public void onFailure(String message) {
				// TODO Auto-generated method stub

			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			resetPasswordTask.execute(username);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}

	}

	private void loginUser() {
		getUserTask = new GetUserTask(LoginRegisterActivity.this);

		getUserTask.setRequestCompleteListener(new RequestCompleteListener<String>() {

			@Override
			public void onSuccess(String result) {
				SharedPreferences.Editor editor = mApp.getHappie_prefs().edit();
				try {
					JSONArray jsonArray = new JSONArray(result);
					JSONObject json = jsonArray.getJSONObject(0);
					if (json.has("apimsg")) {
						JSONObject json1 = json.getJSONObject("apimsg");
						if (json1.has("iduser")) {
							editor.putString(Keys.KEY_USER_ID, json1.getString("iduser"));
							editor.putBoolean(Keys.KEY_USER_LOGGED_IN, true);
							editor.putString(Keys.KEY_USERNAME, username);
							editor.putString(Keys.KEY_PASSWORD, password);
							if (json1.has("profile")) {
								JSONObject json2 = json1.getJSONObject("profile");
								editor.putString(Keys.KEY_NAME, json2.optString("name"));
								editor.putString(Keys.KEY_SURNAME, json2.optString("surname"));
								// editor.putString(Keys.KEY_EMAIL, email);
								editor.putString(Keys.KEY_STREET, json2.optString("street"));
								editor.putString(Keys.KEY_APT_NO, json2.optString("apt"));
								editor.putString(Keys.KEY_ZIP, json2.optString("zip"));
								editor.putString(Keys.KEY_CITY, json2.optString("city"));
								editor.putString(Keys.KEY_PHONE, json2.optString("phone"));
								// editor.putString(Keys.KEY_COUNTRY,
								// json2.optString("country"));
								editor.putString(Keys.KEY_ADDRESS, json2.optString("city") + ", " + json2.optString("street") + ", " + json2.optString("apt") + ", " + json2.optString("zip"));
							}
							
							if (json1.has("orders")) {
								editor.putString(Keys.KEY_ORDERS, json1.getString("orders"));
							}

							editor.commit();
							mApp.setLoggedIn(true);
							mApp.setUserId(json1.getString("iduser"));
						}
						if (json1.has("message")) {
							showMessageDialog(json1.getString("message"));
						}
						if (json1.has("address")) {
							editor.putString(Keys.KEY_ADDRESS, json1.getString("address"));
						}

						editor.commit();
					}
					if (json.has("error")) {
						showErrorDialog(json.getString("error"));
					}

				} catch (Exception e) {
				}
			}

			@Override
			public void onFailure(String message) {
				// TODO Auto-generated method stub

			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			getUserTask.execute(username, password);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	public void showMessageDialog(String message) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog);
		alertDialog.setCancelable(true);

		TextView text = (TextView) alertDialog.findViewById(R.id.dialog_title);
		text.setTextSize(18);
		text.setText(message);

		Button okButton = (Button) alertDialog.findViewById(R.id.ok_button);
		okButton.setText(R.string.ok_error);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
				getFavorites();
			}
		});
		alertDialog.show();
	}

	public void showErrorDialog(String message) {
		if (alertDialog != null && alertDialog.isShowing())
			return;

		alertDialog = new Dialog(this);
		alertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
		alertDialog.setContentView(R.layout.dialog);
		alertDialog.setCancelable(true);

		TextView text = (TextView) alertDialog.findViewById(R.id.dialog_title);
		text.setTextSize(18);
		text.setText(message);

		Button okButton = (Button) alertDialog.findViewById(R.id.ok_button);
		okButton.setText(R.string.ok_error);
		okButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				alertDialog.cancel();
			}
		});
		alertDialog.show();
	}

	private void getFavorites() {

		getFavoritesTask = new GetFavoritesTask(this);
		getFavoritesTask.setRequestCompleteListener(new RequestCompleteListener<List<FavoritesBean>>() {

			@Override
			public void onSuccess(List<FavoritesBean> result) {
				if (mApp == null) {
					setResult(RESULT_CANCELED);
					finish();
					return;
				}
				mApp.getFavorites().clear();
				mApp.addDefaultFavorite();
				for (FavoritesBean favoritesBean : result) {
					for (CompanyBean companyBean : mApp.getCompanies()) {
						if (favoritesBean.getCompanyId().equals(companyBean.getCompanyId())) {

							Common.addFavoriteIfExists(mApp.getFavorites(), companyBean);
							// mApp.getFavorites().add(companyBean);
						}
					}
					mApp.getHappie_prefs().edit().putString("Favorites", Common.companyArrayToJson(mApp.getFavorites())).commit();
				}
				setResult(800);
				finish();
			}

			@Override
			public void onFailure(final String message) {
				runOnUiThread(new Runnable() {

					@Override
					public void run() {
						Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
						mApp.getFavorites().removeAll(mApp.getFavorites());
						setResult(800);
						finish();
					}
				});
			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			getFavoritesTask.execute(mApp.getUserId());
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	public void editTextListeners() {

		userET = (EditText) findViewById(R.id.r_username);
		passET = (EditText) findViewById(R.id.r_password);
		verifyET = (EditText) findViewById(R.id.r_verifyPassword);
		nameET = (EditText) findViewById(R.id.r_name);
		surnameET = (EditText) findViewById(R.id.r_surename);
		// emailET = (EditText) findViewById(R.id.r_email);
		streetET = (EditText) findViewById(R.id.r_street);
		aptnoET = (EditText) findViewById(R.id.r_aptno);
		zipET = (EditText) findViewById(R.id.r_zip);
		cityET = (EditText) findViewById(R.id.r_city);
		phoneET = (EditText) findViewById(R.id.r_phone);
		// countryET = (EditText) findViewById(R.id.r_country);

		// userET.setHint(R.string.username);
		// passET.setHint(R.string.password);
		// verifyET.setHint(R.string.verify);
		// countryET.setHint(R.string.address);

	}

	public void registerButtonListener() {
		Button registerButton = (Button) findViewById(R.id.r_registerBtn);
		registerButton.setText(R.string.register);
		registerButton.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub

				username = userET.getText().toString();
				password = passET.getText().toString();
				verPassword = verifyET.getText().toString();
				name = nameET.getText().toString();
				surname = surnameET.getText().toString();
				// email = emailET.getText().toString();
				street = streetET.getText().toString();
				aptno = aptnoET.getText().toString();
				zip = zipET.getText().toString().replaceAll(" ", "");
				zipET.setText(zip);
				city = cityET.getText().toString();
				phone = phoneET.getText().toString();
				// country = countryET.getText().toString();

				boolean isEmpty = false;
				if (username.equals(Keys.EMPTY_STRING)) {
					userET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_username));
				}

				if (password.equals(Keys.EMPTY_STRING)) {
					passET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_password));
				}
				
				if (name.equals(Keys.EMPTY_STRING)) {
					nameET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_name));
				}
				if (surname.equals(Keys.EMPTY_STRING)) {
					surnameET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_surname));
				}
				// if (email.equals(Keys.EMPTY_STRING)) {
				// showErrorDialog(getString(R.string.empty_email));
				// return;
				// }
				if (street.equals(Keys.EMPTY_STRING)) {
					streetET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_street));
				}
				if (aptno.equals(Keys.EMPTY_STRING)) {
					aptnoET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_aptno));
				}
				if (zip.equals(Keys.EMPTY_STRING)) {
					zipET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_zip));
				}
				if (city.equals(Keys.EMPTY_STRING)) {
					cityET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_city));
				}
				
				if (phone.equals(Keys.EMPTY_STRING)) {
					phoneET.setHintTextColor(getResources().getColor(R.color.red));
					isEmpty = true;
//					showErrorDialog(getString(R.string.empty_city));
				}
				if (!password.equals(verPassword)) {
					showErrorDialog(getString(R.string.pass_dont_match));
					return;
				} else if(isEmpty){
					showErrorDialog(getString(R.string.fill_all_fields));
					return;
				}
				// if (country.equals(Keys.EMPTY_STRING)) {
				// showErrorDialog(getString(R.string.empty_country));
				// return;
				// }

				registerUser();
			}
		});
	}

	private void registerUser() {

		setNewUserTask = new SetNewUserTask(LoginRegisterActivity.this);

		setNewUserTask.setRequestCompleteListener(new RequestCompleteListener<String>() {

			@Override
			public void onSuccess(String result) {
				SharedPreferences.Editor editor = mApp.getHappie_prefs().edit();
				try {
					JSONArray jsonArray = new JSONArray(result);
					JSONObject json = jsonArray.getJSONObject(0);
					if (json.has("apimsg")) {
						JSONObject json1 = json.getJSONObject("apimsg");
						if (json1.has("userid")) {
							editor.putString(Keys.KEY_USER_ID, json1.getString("userid"));
							editor.putBoolean(Keys.KEY_USER_LOGGED_IN, true);
							editor.putString(Keys.KEY_USERNAME, username);
							editor.putString(Keys.KEY_PASSWORD, password);
							editor.putString(Keys.KEY_NAME, name);
							editor.putString(Keys.KEY_SURNAME, surname);
							// editor.putString(Keys.KEY_EMAIL, email);
							editor.putString(Keys.KEY_STREET, street);
							editor.putString(Keys.KEY_APT_NO, aptno);
							editor.putString(Keys.KEY_ZIP, zip);
							editor.putString(Keys.KEY_CITY, city);
							editor.putString(Keys.KEY_PHONE, phone);
							// editor.putString(Keys.KEY_COUNTRY, country);
							editor.putString(Keys.KEY_ADDRESS, city + ", " + street + ", " + aptno + ", " + zip);
							editor.commit();
							mApp.setLoggedIn(true);
							mApp.setUserId(json1.getString("userid"));
						}

						if (json1.has("message")) {
							showMessageDialog(json1.getString("message"));
							return;
						}
					}

					if (json.has("error")) {
						showErrorDialog(json.getString("error"));
						return;
					}
				} catch (Exception e) {
				}
			}

			@Override
			public void onFailure(String message) {
				// TODO Auto-generated method stub

			}
		});
		if (Availablity.isNetworkAvailable(this)) {
			setNewUserTask.execute(username, password, name, surname, street, aptno, zip, city, phone);
		} else {
			Toast.makeText(this, getString(R.string.no_connection), Toast.LENGTH_SHORT).show();
		}
	}

	// private void footerMenuListeners() {
	//
	// View homeButton = findViewById(R.id.home);
	// homeButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// finish();
	// }
	// });
	//
	// View categoriesButton = findViewById(R.id.categories);
	// categoriesButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// if (mApp.isLoggedIn()) {
	// Intent intent = new Intent(LoginRegisterActivity.this,
	// CategoriesActivity.class);
	// intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
	// startActivityForResult(intent, 10);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
	// }
	// }
	// });
	//
	// View basketButton = findViewById(R.id.basket);
	// basketButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	//
	// if (mApp.isLoggedIn()) {
	// Intent intent = new Intent(LoginRegisterActivity.this,
	// BasketActivity.class);
	// intent.putExtra(Keys.KEY_COMPANY_ID, mApp.getCompanyId());
	// startActivityForResult(intent, 10);
	// } else {
	// Toast.makeText(getApplicationContext(),
	// getString(R.string.not_logged_in), Toast.LENGTH_SHORT).show();
	// }
	// }
	// });
	//
	// View searchButton = findViewById(R.id.search);
	// searchButton.setOnClickListener(new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	//
	// }
	// });
	//
	// }

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 100) {
			finish();
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();

		if (getFavoritesTask != null) {
			getFavoritesTask.setRequestCompleteListener(null);
		}

		if (getUserTask != null) {
			getUserTask.setRequestCompleteListener(null);
		}

		if (setNewUserTask != null) {
			setNewUserTask.setRequestCompleteListener(null);
		}

		if (resetPasswordTask != null) {
			resetPasswordTask.setRequestCompleteListener(null);
		}
	}

}
